import React, { Component } from "react";
import utils from "@/common/utils";
import "./index.scss";
const rotateAngle = 90;

interface PropsType {
  data: string;
  callback?: (string) => void;
  hintText?: string;
  alertText?: string;
}
export default class Signature extends Component<PropsType, any> {
  imageTrackGroup: ImageData[];
  canvasBox: HTMLDivElement;
  canvas: HTMLCanvasElement;
  ctx: any;
  constructor(props) {
    super(props);
    this.imageTrackGroup = [];
    this.state = {
      isHint: false,
      data: props.data
    };
  }

  render() {
    return (
      <div className="electr-signatre">
        <div className="btn-box">
          {this.props.hintText && <div className="text">{this.props.hintText}</div>}

          <div className="sub-btn cancle-step" onClick={this.cancleStep}>
            撤回上一步
          </div>
          <div className="sub-btn" onClick={this.clearCanvas}>
            清空
          </div>
          <div className="sub-btn true-btn" onClick={this.canvastourl}>
            确定
          </div>
        </div>
        <div
          className="canvas-box"
          ref={(el) => {
            this.canvasBox = el;
          }}
        >
          {this.state.isHint === true && (
            <p className="hint">{this.props.alertText || '签名内容不能为空'}</p>
          )}
          <canvas
            id="canvas"
            ref={(el) => {
              this.canvas = el;
            }}
          ></canvas>
        </div>
      </div>
    );
  }

  componentDidMount() {
    this.initCanvas();
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.data !== this.state.data) {
      utils.image.rotateBase64Img(nextProps.data, rotateAngle, (base64data) => {
        const img = new Image();
        img.src = base64data;
        img.onload = () => {
          this.ctx.drawImage(img, 0, 0, img.width, img.height);
        };
      });
    }
  }

  initCanvas = () => {
    this.canvas.width = this.canvasBox.offsetWidth;
    this.canvas.height = this.canvasBox.offsetHeight;
    const canvaxOffsetX = this.canvas.offsetLeft;
    const canvaxOffsetY = this.canvas.offsetTop;
    const ctx = this.canvas.getContext("2d");
    this.ctx = ctx;

    if (this.props.data) {
      utils.image.rotateBase64Img(this.props.data, 90, (base64data) => {
        const img = new Image();
        img.src = base64data;
        img.onload = function () {
          ctx.drawImage(img, 0, 0, img.width, img.height);
        };
      });
    }

    this.canvas.addEventListener("touchstart", (e) => {
      e.preventDefault();
      const touchX = e.touches[0].pageX;
      const touchY = e.touches[0].pageY;

      ctx.beginPath();
      ctx.lineWidth = 10;
      // 画笔起始点
      ctx.moveTo(touchX - canvaxOffsetX, touchY - canvaxOffsetY);
      if (this.state.isHint === true) {
        this.setState({
          isHint: false
        });
      }
    });

    this.canvas.addEventListener("touchmove", (e) => {
      e.preventDefault();
      const touchX = e.touches[0].pageX;
      const touchY = e.touches[0].pageY;
      // 根据鼠标路径绘画
      ctx.lineTo(touchX - canvaxOffsetX, touchY - canvaxOffsetY);
      // 立即渲染
      ctx.stroke();
    });

    this.canvas.addEventListener("touchend", (e) => {
      e.preventDefault();
      const imgData = ctx.getImageData(
        0,
        0,
        this.canvas.width,
        this.canvas.height
      );
      console.log('imgData', imgData);
      this.imageTrackGroup.push(imgData);
      ctx.closePath();
    });
  };

  // 判断传入的canvas是否为空
  isBlank = (base64) => {
    const blank = document.createElement("canvas"); // 系统获取一个空canvas对象
    blank.width = this.canvas.width;
    blank.height = this.canvas.height;

    if (blank.toDataURL("image/png") === base64) {
      this.setState({ isHint: true });
    }
  };

  clearCanvas = () => {
    this.imageTrackGroup = [];
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  };

  canvastourl = () => {
    const base64 = this.canvas.toDataURL("image/png");
    this.isBlank(base64);
    utils.image.rotateBase64Img(base64, 270, (base64data) => {
      this.props.callback(base64data);
    });
  };

  cancleStep = () => {
    const ctx = this.canvas.getContext("2d");
    this.imageTrackGroup.pop();
    if (this.imageTrackGroup.length) {
      ctx.putImageData(this.imageTrackGroup[this.imageTrackGroup.length - 1], 0, 0);
    } else {
      this.clearCanvas();
    }
  };
}
